/**
 * This file is part of the CAKIS project.
 * 
 * Copyright (c) 2009-2010 - Florian Arndt, Christian Kerl
 * 
 * @license GNU Lesser General Public License v3 <http://www.opensource.org/licenses/lgpl-3.0.html>
 * @since   14.05.2010
 * @version SVN: $Id: StockUnitCleaner.java 136 2010-05-15 10:36:43Z christian-kerl@web.de $
 */
package org.cakis.server.service.impl;

import java.util.List;

import org.cakis.server.model.StockUnit;
import org.cakis.server.model.repository.StockUnitRepository;
import org.cakis.server.service.StockUnitNotFoundException;

/**
 * StockUnitCleaner
 *
 * @author Christian Kerl
 */
public class StockUnitCleaner {
    private StockUnitRepository repository;

    public StockUnitCleaner(StockUnitRepository repository) {
        this.repository = repository;
    }

    public StockUnit getCleanStockUnit(StockUnit unit) throws StockUnitNotFoundException {
        String nameOrSymbol = null;
        StockUnit result = null;

        // find by name first
        if(unit.getName() != null) {
            nameOrSymbol = unit.getName();
            result = getFirstStockUnitFoundByNameOrSymbol(nameOrSymbol);
        }

        // find by name failed, try find by symbol
        if(result == null && unit.getSymbol() != null) {
            nameOrSymbol = unit.getSymbol();
            result = getFirstStockUnitFoundByNameOrSymbol(nameOrSymbol);
        }

        if(result == null) {
            throw new StockUnitNotFoundException(nameOrSymbol);
        }

        return result;
    }

    private StockUnit getFirstStockUnitFoundByNameOrSymbol(String nameOrSymbol) {
        StockUnit result = null;

        List<StockUnit> list = repository.findByNameOrSymbol(nameOrSymbol);

        if(list.size() > 0) {
            result = list.get(0);
        }

        return result;
    }
}
